package com.example.oauth2.utils;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;

/**
 * @author zty
 * @apiNote
 * @user nav1c
 * @date 2023/12/8 23:49
 * @project study-cloud
 */
public final class SecurityContextUtils {

    private SecurityContextUtils() {
        throw new IllegalStateException("");
    }

    public static SecurityContext getSecurityContext(){
        return SecurityContextHolder.getContext();
    }

    public static void setAuthentication(Authentication authentication) {
        getSecurityContext().setAuthentication(authentication);
    }

    /**
     * 获取当前登录用户的身份认证对象
     * @return 当前登录用户的身份认证对象，如果未登录则返回null
     */
    public static Authentication getCurrentAuthentication() {
        final Authentication authentication = getSecurityContext().getAuthentication();
        if (authentication == null) {
            throw new IllegalStateException("未登录！");
        }
        return authentication;
    }

    /**
     * 获取当前登录用户的用户名
     * @return 当前登录用户的用户名，如果未登录则返回null
     */
    public static String getCurrentUsername() {
        final Authentication authentication = getCurrentAuthentication();
        if (authentication.isAuthenticated()) {
            return authentication.getName();
        }
        throw new IllegalStateException("未授权：" + authentication.getName());
    }

    public static Object getCurrentUserDetails(){
        final Authentication authentication = getCurrentAuthentication();
        if (authentication.isAuthenticated()) {
            return authentication.getDetails();
        }
        throw new IllegalStateException("未授权：" + authentication.getName());
    }

}
